package com.vic.framework.helper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vic.framework.bean.FileParam;
import com.vic.framework.bean.FormParam;
import com.vic.framework.bean.Param;
import com.vic.framework.utils.FileUtil;
import com.vic.framework.utils.StreamUtil;

/**
 * 文件上传助手类
 * @author VIC
 *
 */
public final class UploadHelper {
	
	public static final Logger logger = LoggerFactory.getLogger(UploadHelper.class);
	
	/**
	 * Apache Commons FileUpload提供的Servlet文件上传对象
	 */
	private static ServletFileUpload servletFileUpload;
	
	/**
	 * 初始化
	 */
	public static void init(ServletContext servletContext){
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		servletFileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
		int uploadLimit = ConfigHelper.getAppUploadLimit();
		if(uploadLimit > 0 ){
			servletFileUpload.setFileSizeMax(uploadLimit * 1024 *1024); 
		}
	}
	
	/**
	 * 判断是否为multipart
	 */
	public static boolean isMultipart(HttpServletRequest request) {
		return ServletFileUpload.isMultipartContent(request);
	}
	
	
	/**
	 *  创建请求对象
	 */
	public static Param createParam(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<FormParam>(); 
		List<FileParam> fileParamList = new ArrayList<FileParam>();
		
		try{
			Map<String, List<FileItem>> fileItemListMap = servletFileUpload.parseParameterMap(request);
			if(MapUtils.isNotEmpty(fileItemListMap)) {
				for(Map.Entry<String, List<FileItem>> entry : fileItemListMap.entrySet()) {
					String fieldName = entry.getKey();
					List<FileItem> fileItemList = entry.getValue();
					if(CollectionUtils.isNotEmpty(fileItemList)) {
						for(FileItem item :  fileItemList) {
							if(item.isFormField()) {
								String fieldValue = item.getString("UTF-8");
								formParamList.add(new FormParam(fieldName, fieldValue));
							}else {
								String fileName = FileUtil.getRealFileName(new String(item.getName().getBytes(), "UTF-8"));
								if(StringUtils.isNotEmpty(fileName)) {
									long fileSize = item.getSize();
									String contentType = item.getContentType();
									InputStream inputStream = item.getInputStream();
									fileParamList.add(new FileParam(fieldName, fileName, fileSize, contentType, inputStream));
								}
							}
						}
					}
							
				}
			}
			
		}catch(FileUploadException e){
			logger.error("create param failure", e);
			throw new RuntimeException(e);
		}
		return new Param(formParamList, fileParamList);
	}
	
	
	/**
	 * 上传文件
	 */
	public static void uploadFile(String basePath, FileParam fileParam) {
		try{
			if(fileParam != null) {
				String filePath = basePath + fileParam.getFileName();
				FileUtil.createFile(filePath);
				InputStream inputStream = new BufferedInputStream(fileParam.getInputStream());
				OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
				StreamUtil.copyStream(inputStream, outputStream);
			}
		}catch(Exception e) {
			logger.error("upload file failure", e);
			throw new RuntimeException(e);
		}
	}
	
	
	
}
